package de.argh.codebook.controller;

import java.security.Principal;

import javax.inject.Inject;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import de.argh.codebook.model.Coder;
import de.argh.codebook.model.ValidationResponse;
import de.argh.codebook.service.ArticleService;
import de.argh.codebook.service.CoderService;

@Controller
@RequestMapping("/coder")
public class CoderController {

  @Inject
  private CoderService coderService;
  
  @Inject
  private ArticleService articleService;

  @Inject
  private ValidationHelper validationHelper;
  
  @RequestMapping(value="/{id}", method = RequestMethod.GET)
  public String showProfile(@PathVariable("id") Long id, Model model, Principal principal) {
    Coder coder = coderService.getCoderById(id);
    coder.setFollower(coderService.getFollower(id));
    coder.setArticles(articleService.getArticlesFromCoder(id));
    
    model.addAttribute("isAuthenticatedUser", isAuthenticatedUser(id, principal));
    model.addAttribute("coder", coder);
    return "profileShow";
  }
  
  @RequestMapping(method = RequestMethod.PUT)
  public String saveProfil(@ModelAttribute("coder") @Valid Coder coder, BindingResult result) {
    return "profileShow";
  }
  
  @RequestMapping(value="/validate.json",method = {RequestMethod.PUT, RequestMethod.POST})
  public @ResponseBody ValidationResponse validateProfil(@ModelAttribute("coder") @Valid Coder coder, BindingResult result) {
    return validationHelper.validateBindingResult(result);
  }
  
  @RequestMapping(value="/{id}/edit", method = RequestMethod.GET)
  public String editPofil(@PathVariable("id") Long id, Model model, Principal principal) {
    Coder coder = coderService.getCoderByPrincipalName(principal.getName());
    if (isAuthenticatedUser(id, principal)) {
      model.addAttribute("coder", coder);
      return "profileEdit";
    }
    return "redirect:/coder/" + id;
  }
  
  private boolean isAuthenticatedUser(Long id, Principal principal) {
    Coder coder = coderService.getCoderByPrincipalName(principal.getName());
    return coder.getId().equals(id);
  }
  
}
